<template>
  <div class="user-management">
    <h1 class="page-title">
      <el-icon><User /></el-icon>
      用户管理
    </h1>

    <!-- 搜索和筛选 -->
    <el-card class="search-card mb-20">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户名、邮箱或姓名..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-select v-model="roleFilter" placeholder="选择角色" clearable @change="loadUsers">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-select v-model="statusFilter" placeholder="选择状态" clearable @change="loadUsers">
            <el-option label="活跃" value="active" />
            <el-option label="非活跃" value="inactive" />
            <el-option label="已禁用" value="banned" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="4">
          <el-button type="primary" @click="loadUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="user-list-card">
      <template #header>
        <div class="list-header">
          <span>用户列表 (共 {{ pagination.total }} 人)</span>
          <el-button type="success" size="small" @click="exportUsers">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="real_name" label="真实姓名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="role" label="角色" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)" size="small">
              {{ getRoleLabel(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_study_days" label="学习天数" width="100" align="center" />
        <el-table-column prop="continuous_checkin_days" label="连续打卡" width="100" align="center" />
        <el-table-column prop="createdAt" label="注册时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="last_login_at" label="最后登录" width="180">
          <template #default="{ row }">
            {{ row.last_login_at ? formatDate(row.last_login_at) : '从未登录' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="viewUserDetail(row)">
                <el-icon><View /></el-icon>
              </el-button>
              <el-button size="small" type="primary" @click="editUser(row)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                size="small"
                :type="row.status === 'active' ? 'warning' : 'success'"
                @click="toggleUserStatus(row)"
              >
                <el-icon><Switch /></el-icon>
              </el-button>
              <el-button size="small" type="danger" @click="deleteUser(row)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>

    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="用户详情"
      width="800px"
      class="user-detail-dialog"
    >
      <div v-if="currentUser" class="user-detail">
        <div class="detail-header">
          <div class="user-avatar">
            <img v-if="currentUser.avatar" :src="currentUser.avatar" :alt="currentUser.username" />
            <el-icon v-else class="avatar-icon"><User /></el-icon>
          </div>
          <div class="user-basic-info">
            <h2>{{ currentUser.real_name || currentUser.username }}</h2>
            <p>{{ currentUser.email }}</p>
            <div class="user-tags">
              <el-tag :type="getRoleType(currentUser.role)">{{ getRoleLabel(currentUser.role) }}</el-tag>
              <el-tag :type="getStatusType(currentUser.status)">{{ getStatusLabel(currentUser.status) }}</el-tag>
            </div>
          </div>
        </div>

        <el-divider />

        <div class="detail-stats">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ userStats.totalProgress || 0 }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ userStats.completedProgress || 0 }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ userStats.totalCheckins || 0 }}</div>
                <div class="stat-label">总打卡数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ currentUser.continuous_checkin_days || 0 }}</div>
                <div class="stat-label">连续打卡</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="recent-checkins" v-if="userStats.recentCheckins?.length">
          <h3>最近打卡记录</h3>
          <el-table :data="userStats.recentCheckins" size="small">
            <el-table-column prop="checkin_date" label="日期" width="120" />
            <el-table-column prop="study_content" label="学习内容" />
            <el-table-column prop="study_hours" label="学习时长" width="100" />
            <el-table-column prop="completion_rate" label="完成度" width="100">
              <template #default="{ row }">
                {{ row.completion_rate }}/5
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑用户"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="real_name">
          <el-input v-model="editForm.real_name" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" style="width: 100%">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" style="width: 100%">
            <el-option label="活跃" value="active" />
            <el-option label="非活跃" value="inactive" />
            <el-option label="已禁用" value="banned" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

// 状态数据
const loading = ref(false)
const users = ref([])
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const showDetailDialog = ref(false)
const showEditDialog = ref(false)
const currentUser = ref(null)
const userStats = ref({})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 编辑表单
const editForm = ref({
  id: null,
  username: '',
  email: '',
  real_name: '',
  role: 'student',
  status: 'active'
})

const editFormRef = ref()
const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      search: searchQuery.value,
      role: roleFilter.value,
      status: statusFilter.value
    }

    const response = await api.get('/admin/users', { params })
    if (response.data.success) {
      users.value = response.data.data.users
      pagination.value.total = response.data.data.total
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.value.page = 1
  loadUsers()
}

// 排序处理
const handleSortChange = ({ prop, order }) => {
  // 实现排序逻辑
  loadUsers()
}

// 查看用户详情
const viewUserDetail = async (user) => {
  try {
    const response = await api.get(`/admin/users/${user.id}`)
    if (response.data.success) {
      currentUser.value = response.data.data.user
      userStats.value = response.data.data.statistics
      showDetailDialog.value = true
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 编辑用户
const editUser = (user) => {
  editForm.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    real_name: user.real_name || '',
    role: user.role,
    status: user.status
  }
  showEditDialog.value = true
}

// 保存用户信息
const saveUser = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    
    const response = await api.put(`/admin/users/${editForm.value.id}`, editForm.value)
    if (response.data.success) {
      ElMessage.success('用户信息更新成功')
      showEditDialog.value = false
      loadUsers()
    }
  } catch (error) {
    if (error.name === 'ValidationError') return
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败')
  }
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  const newStatus = user.status === 'active' ? 'inactive' : 'active'
  const statusText = newStatus === 'active' ? '激活' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}用户 ${user.username} 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await api.put(`/admin/users/${user.id}/status`, {
      status: newStatus
    })

    if (response.data.success) {
      ElMessage.success(`用户已${statusText}`)
      loadUsers()
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('更新用户状态失败:', error)
    ElMessage.error('更新用户状态失败')
  }
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    const response = await api.delete(`/admin/users/${user.id}`)
    if (response.data.success) {
      ElMessage.success('用户删除成功')
      loadUsers()
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除用户失败:', error)
    ElMessage.error('删除用户失败')
  }
}

// 导出用户数据
const exportUsers = async () => {
  try {
    const response = await api.get('/admin/export/users')
    if (response.data.success) {
      // 创建下载链接
      const blob = new Blob([JSON.stringify(response.data.data, null, 2)], {
        type: 'application/json'
      })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `users_${new Date().toISOString().split('T')[0]}.json`
      a.click()
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('用户数据导出成功')
    }
  } catch (error) {
    console.error('导出用户数据失败:', error)
    ElMessage.error('导出用户数据失败')
  }
}

// 工具函数
const getRoleType = (role) => {
  const typeMap = {
    'student': 'info',
    'teacher': 'warning',
    'admin': 'danger'
  }
  return typeMap[role] || 'info'
}

const getRoleLabel = (role) => {
  const labelMap = {
    'student': '学生',
    'teacher': '教师',
    'admin': '管理员'
  }
  return labelMap[role] || role
}

const getStatusType = (status) => {
  const typeMap = {
    'active': 'success',
    'inactive': 'warning',
    'banned': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusLabel = (status) => {
  const labelMap = {
    'active': '活跃',
    'inactive': '非活跃',
    'banned': '已禁用'
  }
  return labelMap[status] || status
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 组件挂载
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

/* 通用样式 */
.mb-20 {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
}

.page-title .el-icon {
  margin-right: 12px;
  color: #409eff;
  font-size: 28px;
}

/* 搜索卡片 */
.search-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

/* 用户列表 */
.user-list-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 用户详情 */
.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-icon {
  font-size: 40px;
  color: #ccc;
}

.user-basic-info h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.user-basic-info p {
  margin: 0 0 12px 0;
  color: #606266;
}

.user-tags {
  display: flex;
  gap: 8px;
}

.detail-stats {
  margin: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.recent-checkins {
  margin-top: 20px;
}

.recent-checkins h3 {
  margin: 0 0 12px 0;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 20px;
  }
  
  .detail-header {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-item {
    padding: 16px;
  }
  
  .stat-number {
    font-size: 20px;
  }
}
</style> 